package com.itcam.otcbackend.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.itcam.otcbackend.annotation.AuthCheck;
import com.itcam.otcbackend.api.aliyunai.AliYunAiApi;
import com.itcam.otcbackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.itcam.otcbackend.api.aliyunai.model.CreatePictureOutPaintingTaskRequest;
import com.itcam.otcbackend.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.itcam.otcbackend.auth.SpaceUserAuthManager;
import com.itcam.otcbackend.auth.StpKit;
import com.itcam.otcbackend.auth.annotation.SaSpaceCheckPermission;
import com.itcam.otcbackend.auth.model.SpaceUserPermissionConstant;
import com.itcam.otcbackend.common.BaseResponse;
import com.itcam.otcbackend.common.DeleteRequest;
import com.itcam.otcbackend.constant.UserConstant;
import com.itcam.otcbackend.enums.ErrorCode;
import com.itcam.otcbackend.enums.PictureReviewStatusEnum;
import com.itcam.otcbackend.exception.BusinessException;
import com.itcam.otcbackend.api.imagesearch.ImageSearchApiFacade;
import com.itcam.otcbackend.api.imagesearch.model.ImageSearchResult;
import com.itcam.otcbackend.model.dto.imagesearch.SearchPictureByColorRequest;
import com.itcam.otcbackend.model.dto.imagesearch.SearchPictureByPictureRequest;
import com.itcam.otcbackend.model.dto.picture.*;
import com.itcam.otcbackend.model.po.Picture;
import com.itcam.otcbackend.model.po.Space;
import com.itcam.otcbackend.model.po.User;
import com.itcam.otcbackend.model.vo.PictureTagCategory;
import com.itcam.otcbackend.model.vo.PictureVO;
import com.itcam.otcbackend.service.PictureService;
import com.itcam.otcbackend.service.SpaceService;
import com.itcam.otcbackend.service.UserService;
import com.itcam.otcbackend.utils.ResultUtils;
import com.itcam.otcbackend.utils.ThrowUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();


    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @ApiOperation("上传图片（可重新上传）")
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 上传图片
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        // 返回上传结果
        return ResultUtils.success(pictureVO);
    }

    // 通过 URL 上传图片（可重新上传）
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl() {
        return null;
    }

    /**
     * 更新图片（仅管理员可用）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 添加审核参数
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间的图片，需要校验权限
        Space space = null;
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
//            User loginUser = userService.getLoginUser(request);
//            pictureService.checkPictureAuth(loginUser, picture);
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 获取权限列表
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 公开图库
        if (null == spaceId) {
            // 普通用户默认只能查看已过审的数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
//            // 私有空间
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
        }
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 获取预置标签和分类
     * 在项目前期规模不大的时候，没必要将标签和分类单独用数据表来维护，直接在PictureController中写一个接口来返回预设的固定数据即可
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 审核图片
     * @param pictureReviewRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * todo
     *      图片优化：
     *          查询优化 - 分布式缓存、本地缓存、多级缓存
     *          上传优化 - 压缩、秒传、分片上传、断点续传
     *          加载优化 - 懒加载、缩略图、CDN加速、浏览器缓存
     *          存储优化 - 降频存储（冷热数据分离）、清理策略
     */

    /**
     * 使用缓存份分页查询图片列表
     * todo:考虑到私有空间的图片更新频率不好把握，先把这个接口标记为@Deprecated
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo/cache")
    @Deprecated
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        int current = pictureQueryRequest.getCurrent();
        int size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 普通用户默认只能查看已过审的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = "campicture:listPictureVOByPage:" + hashKey;

        // 1.从本地缓存中查询(Caffeine)
        String cacheValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (null != cacheValue) {
            Page<PictureVO> cachePage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        // 2.查询分布式缓存（Redis）
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        cacheValue = valueOps.get(cacheKey);
        if (null != cacheValue) {
            // 如果缓存命中，先缓存到本地缓存，再返回结果
            LOCAL_CACHE.put(cacheKey, cacheValue);
            Page<PictureVO> cachePage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        // 3.查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 4.更新缓存
        String newCacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 更新本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 更新redis缓存，设置过期时间为分钟
        valueOps.set(cacheKey, newCacheValue, 5, TimeUnit.MINUTES);

        // 返回结果
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 批量抓取和创建图片
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量抓取和创建图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 删除空间图片
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除空间图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 以图搜图
     *
     * @param searchPictureByPictureRequest 以图搜图的请求对象，包含用于搜索的图片的相关信息
     * @return 返回包含图片搜索结果的列表的基础响应对象
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        // 检查请求对象是否为空，如果为空则抛出参数错误异常
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        // 从请求对象中获取图片ID
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        // 检查图片ID是否为空或小于等于0，如果是则抛出参数错误异常
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        // 根据图片ID从数据库中获取图片信息
        Picture oldPicture = pictureService.getById(pictureId);
        // 检查图片是否存在，如果不存在则抛出未找到错误异常
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 调用图片搜索API，传入图片的URL进行搜索，获取搜索结果列表
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        // 将搜索结果封装到基础响应对象中并返回
        return ResultUtils.success(resultList);
    }

    /**
     * 按颜色搜索图片
     *
     * @param searchPictureByColorRequest 按颜色搜索图片的请求对象，包含搜索所需的颜色和空间ID等信息
     * @param request HTTP请求对象，用于获取当前登录用户的信息
     * @return 返回包含符合颜色条件的图片封装对象列表的基础响应对象
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        // 检查请求对象是否为空，如果为空则抛出参数错误异常
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        // 从请求对象中获取图片颜色
        String picColor = searchPictureByColorRequest.getPicColor();
        // 从请求对象中获取空间ID
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 调用图片服务的按颜色搜索图片方法，获取搜索结果
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        // 将搜索结果封装到基础响应对象中并返回
        return ResultUtils.success(result);
    }

    /**
     * 批量编辑图片
     *
     * @param pictureEditByBatchRequest 批量编辑图片的请求对象，包含了需要批量编辑的图片的相关信息，如图片 ID 列表、要修改的属性等
     * @param request HTTP 请求对象，用于获取当前登录用户的信息，以进行权限验证等操作
     * @return 返回一个基础响应对象，包含操作结果（布尔值），true 表示批量编辑操作成功
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        // 检查请求对象是否为空，若为空则抛出参数错误异常
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 调用图片服务的批量编辑图片方法
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        // 返回操作成功的响应
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     *
     * @param createPictureOutPaintingTaskRequest 创建 AI 扩图任务的请求体，包含任务所需的参数
     * @param request HTTP 请求对象，用于获取当前登录用户信息
     * @return 包含创建 AI 扩图任务响应结果的基础响应对象
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            // 接收创建 AI 扩图任务的请求体
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            // 接收 HTTP 请求对象
            HttpServletRequest request) {
        // 检查请求体和请求体中的图片 ID 是否为空，若为空则抛出参数错误异常
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 从请求中获取当前登录用户信息
        User loginUser = userService.getLoginUser(request);
        // 调用图片服务的创建 AI 扩图任务方法，并传入请求体和登录用户信息
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        // 将创建任务的响应结果封装到基础响应对象中并返回
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     *
     * @param taskId 要查询的 AI 扩图任务的 ID
     * @return 包含查询 AI 扩图任务响应结果的基础响应对象
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(
            // 接收要查询的任务 ID
            String taskId) {
        // 检查任务 ID 是否为空，若为空则抛出参数错误异常
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        // 调用阿里云 AI 接口查询指定 ID 的 AI 扩图任务
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        // 将查询任务的响应结果封装到基础响应对象中并返回
        return ResultUtils.success(task);
    }




}
